package com.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.mapper.ChannelMapper;
import com.chen.pojo.dto.ChannelDetailDto;
import com.chen.pojo.dto.ChannelDto;
import com.chen.pojo.entry.Channel;
import com.chen.pojo.vo.ChannelVo;
import com.chen.service.ChannelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chen
 * @version 1.0
 * @create_date 2025/8/22
 * 货道业务管理实现类
 */
@Service
public class ChannelServiceImpl extends ServiceImpl<ChannelMapper, Channel> implements ChannelService {
    @Autowired
    private ChannelMapper channelMapper;

    /**
     * 获取售货机货道详情
     *
     * @param innerCode 机器编号
     * @return 结果
     */
    @Override
    public List<ChannelVo> getChannelList(String innerCode) {
        return channelMapper.selectAllChannel(innerCode);
    }

    /**
     * 货道配置
     *
     * @param channelDto 配置信息
     * @return 结果
     */
    @Override
    public Boolean channelConfig(ChannelDto channelDto) {
        List<Channel> targetList = new ArrayList<>();
        String innerCode = channelDto.getInnerCode();
        LambdaQueryWrapper<Channel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Channel::getInnerCode, innerCode);
        List<Channel> channelList = super.list(wrapper);
        Map<String, String> channelMap = null;
        if (!CollectionUtils.isEmpty(channelList)) {
            channelMap = channelList.stream().collect(
                    Collectors.toMap(Channel::getChannelCode, Channel::getChannelId));
        }

        List<ChannelDetailDto> requestChannelList = channelDto.getChannelList();
        if (!CollectionUtils.isEmpty(requestChannelList) && Objects.nonNull(channelMap)) {
            Map<String, String> targetMap = channelMap;
            requestChannelList.forEach(s -> {
                Channel channel = new Channel();
                channel.setChannelId(targetMap.get(s.getChannelCode()));
                channel.setInnerCode(innerCode);
                channel.setChannelCode(s.getChannelCode());
                channel.setSkuId(s.getSkuId());
                targetList.add(channel);
            });
        }
        super.updateBatchById(targetList);
        return true;
    }
}
